package user;

import java.io.DataOutput;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class User_LoginServlet
 */
@WebServlet("/User_LoginServlet")
public class User_LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public User_LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		//1-接收视图上的数据
		String uname = request.getParameter("uname");
		String pass = request.getParameter("pass");
		 String PicCode = (String)session.getAttribute("PicCode");
		 String checkcode = request.getParameter("CheckCode");
		// System.out.println(checkcode);
		 
		//2-把数据传到JavaBean去执行
		UserDao dao  = new UserDao();
		String ps = dao.string2MD5(pass);
		boolean result = dao.isLogin(uname, ps);
		//3-处理结果，根据结果选择视图
		if(result&&PicCode.equals(checkcode)) {
			//登录成功
			//(1)把完整用户信息查询处理，存到Session里面
			User user = dao.getUserByUname(uname);
			session.setAttribute("user", user);
			session.setAttribute("user1", user);
			//(2)跟新在线人数
			//在线人数的增加
			ServletContext application = request.getServletContext();
			String cournter = (String)application.getAttribute("cournter");
			int count;
			if(cournter == null){
				count = 0;
			}else{
				count = Integer.parseInt(cournter);
			}
			//自增
			count ++;
			application.setAttribute("cournter", String.valueOf(count));
			//response.sendRedirect("./content/main.jsp");
			response.getWriter().print("<script type=\"text/javascript\">alert(\"登录成功！\");window.location=\"./content/main.jsp\";</script>");
		}else {
			//response.sendRedirect("./user/login_failure.jsp");//登录失败
			response.getWriter().print("<script type=\"text/javascript\">alert(\"登录失败！\");window.location=\"/Lesson_310/user/login.jsp\";</script>");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
